/*
 * EasyCamera
 *
 * Copyright (c) 2020.  Frezrik frezrik@126.com
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

package com.camera.widget;

import android.opengl.GLES20;
import android.util.Log;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

public class YuvProgram {
    private FloatBuffer vertexBuffer;
    private FloatBuffer textureBuffer;

    private boolean isProgBuilt = false;
    private int program_yuv;
    private int avPosition_yuv;
    private int afPosition_yuv;

    private int sampler_y;
    private int sampler_u;
    private int sampler_v;
    private int[] textureId_yuv;

    //渲染用
    private int width_yuv;
    private int height_yuv;
    private ByteBuffer y;
    private ByteBuffer u;
    private ByteBuffer v;
    private ByteBuffer blackUV;

    public YuvProgram() {
        //存储顶点坐标数据
        vertexBuffer = ByteBuffer.allocateDirect(vertexData.length * 4)
                .order(ByteOrder.nativeOrder())
                .asFloatBuffer()
                .put(vertexData);
        vertexBuffer.position(0);

        //存储纹理坐标
        textureBuffer = ByteBuffer.allocateDirect(textureData.length * 4)
                .order(ByteOrder.nativeOrder())
                .asFloatBuffer()
                .put(textureData);
        textureBuffer.position(0);
    }

    //yuv转rgb的Shader
    String VERTEX_SHADER = "uniform mat4 uMVPMatrix;\n" + "attribute vec4 av_Position;\n" + "attribute vec2 af_Position;\n" + "varying vec2 tc;\n"
            + "void main()\n" + "{\n" + "gl_Position = uMVPMatrix * av_Position;\n" + "tc = af_Position;\n" + "}\n";

    String FRAGMENT_SHADER = "varying lowp vec2 tc;\n" + "uniform sampler2D sampler_y;\n" + "uniform sampler2D sampler_u;\n"
            + "uniform sampler2D sampler_v;\n" + "void main(void)\n" + "{\n" + "mediump vec3 yuv;\n"
            + "lowp vec3 rgb;\n" + "yuv.x = texture2D(sampler_y, tc).r;\n"
            + "yuv.y = texture2D(sampler_u, tc).r - 0.5;\n" + "yuv.z = texture2D(sampler_v, tc).r - 0.5;\n"
            + "rgb = mat3( 1,   1,   1,\n" + "0,       -0.39465,  2.03211,\n" + "1.13983,   -0.58060,  0) * yuv;\n"
            + "gl_FragColor = vec4(rgb, 1);\n" + "}\n";


    private float[] mViewMatrix = new float[16];
    private int mVPMatrixHandle = -1;
    static float[] s0Matrix = new float[]{1.0F, 0.0F, 0.0F, 0.0F, 0.0F, 1.0F, 0.0F, 0.0F, 0.0F, 0.0F, 1.0F, 0.0F, 0.0F, 0.0F, 0.0F, 1.0F};
    static float[] s0MirrorMatrix = new float[]{-1.0F, 0.0F, 0.0F, 0.0F, 0.0F, 1.0F, 0.0F, 0.0F, 0.0F, 0.0F, 1.0F, 0.0F, 0.0F, 0.0F, 0.0F, 1.0F};
    static float[] s90Matrix = new float[]{0.0F, -1.0F, 0.0F, 0.0F, 1.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 1.0F, 0.0F, 0.0F, 0.0F, 0.0F, 1.0F};
    static float[] s90MirrorMatrix = new float[]{0.0F, -1.0F, 0.0F, 0.0F, -1.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 1.0F, 0.0F, 0.0F, 0.0F, 0.0F, 1.0F};
    static float[] s180Matrix = new float[]{-1.0F, 0.0F, 0.0F, 0.0F, 0.0F, -1.0F, 0.0F, 0.0F, 0.0F, 0.0F, 1.0F, 0.0F, 0.0F, 0.0F, 0.0F, 1.0F};
    static float[] s180MirrorMatrix = new float[]{1.0F, 0.0F, 0.0F, 0.0F, 0.0F, -1.0F, 0.0F, 0.0F, 0.0F, 0.0F, 1.0F, 0.0F, 0.0F, 0.0F, 0.0F, 1.0F};
    static float[] s270Matrix = new float[]{0.0F, 1.0F, 0.0F, 0.0F, -1.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 1.0F, 0.0F, 0.0F, 0.0F, 0.0F, 1.0F};
    static float[] s270MirrorMatrix = new float[]{0.0F, 1.0F, 0.0F, 0.0F, 1.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 1.0F, 0.0F, 0.0F, 0.0F, 0.0F, 1.0F};

    private final float[] vertexData = {//顶点坐标
            -1f, -1f,
            1f, -1f,
            -1f, 1f,
            1f, 1f
    };

    private final float[] textureData = {//纹理坐标
            0f, 1f,
            1f, 1f,
            0f, 0f,
            1f, 0f
    };

    /**
     * 创建prog
     */
    public void buildProgram() {
        //创建一个渲染程序
        if (program_yuv <= 0)
            program_yuv = createProgram(VERTEX_SHADER, FRAGMENT_SHADER);

        //得到着色器中的属性
        avPosition_yuv = GLES20.glGetAttribLocation(program_yuv, "av_Position");
        afPosition_yuv = GLES20.glGetAttribLocation(program_yuv, "af_Position");

        sampler_y = GLES20.glGetUniformLocation(program_yuv, "sampler_y");
        sampler_u = GLES20.glGetUniformLocation(program_yuv, "sampler_u");
        sampler_v = GLES20.glGetUniformLocation(program_yuv, "sampler_v");

        mVPMatrixHandle = GLES20.glGetUniformLocation(program_yuv, "uMVPMatrix");

        //创建纹理
        textureId_yuv = new int[3];
        GLES20.glGenTextures(3, textureId_yuv, 0);

        for (int i = 0; i < 3; i++) {
            //绑定纹理
            GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId_yuv[i]);
            //设置环绕和过滤方式
            GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_REPEAT);
            GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_REPEAT);
            GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
            GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
        }

        isProgBuilt = true;
    }

    /**
     * 渲染
     */
    public void drawFrame() {
        if (width_yuv > 0 && height_yuv > 0 && y != null && u != null && v != null) {
            GLES20.glUseProgram(program_yuv);//使用源程序

            GLES20.glUniformMatrix4fv(mVPMatrixHandle, 1, false, mViewMatrix, 0);

            GLES20.glEnableVertexAttribArray(avPosition_yuv);//使顶点属性数组有效
            GLES20.glVertexAttribPointer(avPosition_yuv, 2, GLES20.GL_FLOAT, false, 8, vertexBuffer);//为顶点属性赋值

            GLES20.glEnableVertexAttribArray(afPosition_yuv);
            GLES20.glVertexAttribPointer(afPosition_yuv, 2, GLES20.GL_FLOAT, false, 8, textureBuffer);

            GLES20.glActiveTexture(GLES20.GL_TEXTURE0);//激活纹理
            GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId_yuv[0]);//绑定纹理
            GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_LUMINANCE, width_yuv, height_yuv, 0, GLES20.GL_LUMINANCE, GLES20.GL_UNSIGNED_BYTE, y);//

            GLES20.glActiveTexture(GLES20.GL_TEXTURE1);
            GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId_yuv[1]);
            GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_LUMINANCE, width_yuv / 2, height_yuv / 2, 0, GLES20.GL_LUMINANCE, GLES20.GL_UNSIGNED_BYTE, u);

            GLES20.glActiveTexture(GLES20.GL_TEXTURE2);
            GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId_yuv[2]);
            GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_LUMINANCE, width_yuv / 2, height_yuv / 2, 0, GLES20.GL_LUMINANCE, GLES20.GL_UNSIGNED_BYTE, v);

            GLES20.glUniform1i(sampler_y, 0);
            GLES20.glUniform1i(sampler_u, 1);
            GLES20.glUniform1i(sampler_v, 2);

            y.clear();
            u.clear();
            v.clear();
            y = null;
            u = null;
            v = null;

            GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
        }
    }
    public void setResolution(int width, int height) {
        this.width_yuv = width;
        this.height_yuv = height;
    }

    public void setYUVRenderData(byte[] y, byte[] u, byte[] v)
    {
        this.y = ByteBuffer.wrap(y);
        this.u = ByteBuffer.wrap(u);
        this.v = ByteBuffer.wrap(v);
    }

    public void setDisplayOrientation(int degrees, boolean needMirror) {
        if (degrees == 0) {
            if (needMirror) {
                this.mViewMatrix = s0MirrorMatrix;
            } else {
                this.mViewMatrix = s0Matrix;
            }
        } else if (degrees == 90) {
            if (needMirror) {
                this.mViewMatrix = s90MirrorMatrix;
            } else {
                this.mViewMatrix = s90Matrix;
            }
        } else if (degrees == 180) {
            if (needMirror) {
                this.mViewMatrix = s180MirrorMatrix;
            } else {
                this.mViewMatrix = s180Matrix;
            }
        } else if (degrees == 270) {
            if (needMirror) {
                this.mViewMatrix = s270MirrorMatrix;
            } else {
                this.mViewMatrix = s270Matrix;
            }
        }

    }

    public boolean isProgramBuilt() {
        return isProgBuilt;
    }

    public void releaseProgram() {
        GLES20.glUseProgram(0);
        if (program_yuv >= 0) {
            GLES20.glDeleteProgram(program_yuv);
        }

        program_yuv = -1;
        isProgBuilt = false;
    }

    private int loadShader(int shaderType, String source) {
        int shader = GLES20.glCreateShader(shaderType);
        if (shader != 0) {
            GLES20.glShaderSource(shader, source);
            GLES20.glCompileShader(shader);
            int[] compile = new int[1];
            GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compile, 0);
            if (compile[0] != GLES20.GL_TRUE) {
                Log.e("paxir", "shader compile error");
                GLES20.glDeleteShader(shader);
                shader = 0;
            }
        }
        return shader;
    }

    private int createProgram(String vertexSource, String fragmentSource) {
        int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexSource);
        if (vertexShader == 0) {
            return 0;
        }
        int fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource);
        if (fragmentShader == 0) {
            return 0;
        }
        int program = GLES20.glCreateProgram();
        if (program != 0) {
            GLES20.glAttachShader(program, vertexShader);
            GLES20.glAttachShader(program, fragmentShader);
            GLES20.glLinkProgram(program);
            int[] linsStatus = new int[1];
            GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linsStatus, 0);
            if (linsStatus[0] != GLES20.GL_TRUE) {
                Log.e("paxir", "link program error");
                GLES20.glDeleteProgram(program);
                program = 0;
            }
        }
        return program;
    }

    private void initBlackUV() {
        int size = width_yuv * height_yuv;
        if (blackUV != null && blackUV.capacity() >= size / 4) {
            blackUV.position(0);
        } else {
            blackUV = ByteBuffer.allocate(size / 4);
            blackUV.position(0);

            for(int i = 0; i < size / 4; ++i) {
                blackUV.put((byte)-128);
            }

            blackUV.position(0);
        }

    }

    public void clear(YuvSurfaceView surfaceView) {
        if (y != null && u != null && v != null) {
            int size = width_yuv * height_yuv;
            byte[] b = new byte[size];
            this.initBlackUV();
            synchronized(this) {
                this.y.clear();
                this.u.clear();
                this.v.clear();
                this.y.put(b);
                this.blackUV.position(0);
                this.u.put(this.blackUV);
                this.blackUV.position(0);
                this.v.put(this.blackUV);
            }

            surfaceView.requestRender();
        }
    }
}
